package com.jinlejia.erp.ui.common;

import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.RadioGroup;
import android.widget.Toast;

import androidx.annotation.Nullable;
import androidx.core.app.ActivityCompat;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentActivity;
import androidx.fragment.app.FragmentTransaction;

import com.hjq.permissions.OnPermission;
import com.hjq.permissions.Permission;
import com.hjq.permissions.XXPermissions;
import com.jinlejia.erp.BuildConfig;
import com.jinlejia.erp.R;
import com.jinlejia.erp.base.unicorn.UnicornUtils;
import com.jinlejia.erp.ui.customer.CustomerFragment;
import com.jinlejia.erp.ui.home.HomeFragment;
import com.jinlejia.erp.ui.house.HouseFragment;
import com.jinlejia.erp.ui.message.MessageFragment;
import com.jinlejia.erp.ui.mine.PersonalFragment;
import com.jinlejia.erp.ui.mine.sign.SignInActivity;
import com.jinlejia.erp.utils.SharePTool;
import com.lab.Lab;
import com.qiyukf.nimlib.sdk.NimIntent;
import com.utils.updateapp.UpdateUtils;

import org.simple.eventbus.EventBus;
import org.simple.eventbus.Subscriber;

import java.util.ArrayList;
import java.util.List;

public class MainActivity extends FragmentActivity {


    //定义一个布局
    private LayoutInflater layoutInflater;

    //装Fragment的实例集合
    private ArrayList<Fragment> fragments;

    //缓存Fragment或上次显示的Fragment
    private Fragment tempFragment;

    PermissionDialog permissionDialog;


    private int position = 0;
    private RadioGroup rgMain;

    //动态授权
    final int REQUEST_EXTERNAL_STORAGE = 1;
    String[] PERMISSIONS_STORAGE = {
            Manifest.permission.READ_EXTERNAL_STORAGE,
            Manifest.permission.WRITE_EXTERNAL_STORAGE};



    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
//        ActivityStack.add(this);
        setContentView(R.layout.activity_main);
        EventBus.getDefault().register(this);
        initView();
        //设置RadioGroup的监听
        initListener();
        if (getIntent().hasExtra("url") && !TextUtils.isEmpty(getIntent().getStringExtra("url"))) { //有link
            sendPush(getIntent());
        }
        if (getIntent().hasExtra("code") && !TextUtils.isEmpty(getIntent().getStringExtra("code"))) {
            if (getIntent().getStringExtra("code").equals("signDeviceRemindCode")) {
                Intent intent1 = new Intent(MainActivity.this, SignInActivity.class);
                intent1.putExtra("MainStartSign", "MainStartSign");
                startActivity(intent1);
            }
        }else {
            Intent intent = getIntent();
            if (intent.hasExtra(NimIntent.EXTRA_NOTIFY_CONTENT)) {
                SharePTool.UserInfoBean userInfoBean = SharePTool.getUserInfoBean(this);
                UnicornUtils.registerAndOpenUnicorn(this,userInfoBean);
            }
        }
    }


    private void initListener() {
        rgMain.check(R.id.rb_home);
        final int [] pos;
        if (BuildConfig.bbsActivity==null){
            pos = new int[]{0,1,2,3,4};
        }else {
            pos = new int[]{0,1,2,3,3};
        }
        rgMain.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup radioGroup, int i) {


                switch (i) {
                    case R.id.rb_home: //首页
                        position = pos[0];
                        break;
                    case R.id.rb_house: //分类
                        position = pos[1];
                        break;
                    case R.id.rb_custom: //发现
                        position = pos[2];
                        break;
                    case R.id.rb_message: //消息
                        position = pos[3];
                        break;
                    case R.id.rb_mine: //个人中心
                        position = pos[4];
                        break;
                    default:
                        position = 0;
                        break;
                }
                //根据位置得到相应的Fragment
                Fragment fragment = getFragment(position);
                /**
                 * 第一个参数: 上次显示的Fragment
                 * 第二个参数: 当前正要显示的Fragment
                 */
                switchFragment(tempFragment, fragment);
            }
        });
    }

    /**
     * 切换Fragment
     *
     * @param fragment
     * @param nextFragment
     */
    private void switchFragment(Fragment fragment, Fragment nextFragment) {
        if (tempFragment != nextFragment) {
            tempFragment = nextFragment;
            if (nextFragment != null) {
                FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
                //判断nextFragment是否添加成功
                if (!nextFragment.isAdded()) {
                    //隐藏当前的Fragment
                    if (fragment != null) {
                        transaction.hide(fragment);
                    }
                    //添加Fragment
                    transaction.add(R.id.realtabcontent, nextFragment).commit();
                } else {
                    //隐藏当前Fragment
                    if (fragment != null) {
                        transaction.hide(fragment);
                    }
                    transaction.show(nextFragment).commit();
                }
                if (nextFragment instanceof HomeFragmentIsShowListener){
                    ((HomeFragmentIsShowListener) nextFragment).onHomeFragmentShow();
                }
            }
        }
    }

    /**
     * 检查更新方法
     */
    public void checkupdate(){
        //检查授权
        int permission = ActivityCompat.checkSelfPermission(this, "android.permission.WRITE_EXTERNAL_STORAGE");
        if (permission != PackageManager.PERMISSION_GRANTED) {
            // 没有写的权限，去申请写的权限，会弹出对话框
            ActivityCompat.requestPermissions( this, PERMISSIONS_STORAGE, REQUEST_EXTERNAL_STORAGE);
        }
        UpdateUtils.getInstance(this).checkAndUpdate(BuildConfig.VERSION_NAME);
    }

    /**
     * 根据位置得到对应的 Fragment
     *
     * @param position
     * @return
     */
    private Fragment getFragment(int position) {
        if (fragments != null && fragments.size() > 0) {
            Fragment fragment = fragments.get(position);
            return fragment;
        }
        return null;
    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        if (intent.hasExtra("url") && !TextUtils.isEmpty(intent.getStringExtra("url"))) { //有link
            sendPush(intent);
        }else if (intent.hasExtra("code") && !TextUtils.isEmpty(intent.getStringExtra("code"))) {
            if (intent.getStringExtra("code").equals("signDeviceRemindCode")) {
                Intent intent1 = new Intent(MainActivity.this, SignInActivity.class);
                intent1.putExtra("MainStartSign", "MainStartSign");
                startActivity(intent1);
            }
        }
        if (intent.hasExtra(NimIntent.EXTRA_NOTIFY_CONTENT)) {
            UnicornUtils.openUnicorn(this);
            setIntent(new Intent()); //清空Intent
        }
    }

    private void sendPush(Intent intent){
        if (intent==null)return;
        String code = intent.getStringExtra("code");
        String link = intent.getStringExtra("url");
        Lab.mainPushProtocol().sendMainPush(this,code,link);
    }

    @Override
    protected void onStart() {
        super.onStart();
        permissionDialog = new PermissionDialog(MainActivity.this);
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (tempFragment!=null && tempFragment instanceof HomeFragmentIsShowListener){
            ((HomeFragmentIsShowListener) tempFragment).onHomeFragmentShow();
        }
        //检查权限
        XXPermissions.with(this)
                .permission(Permission.CALL_PHONE, Permission.READ_PHONE_STATE,
                        Permission.CAMERA,
                        Permission.READ_EXTERNAL_STORAGE, Permission.WRITE_EXTERNAL_STORAGE)
                .request(new OnPermission() {

                    @Override
                    public void hasPermission(List<String> granted, boolean isAll) {
                        System.out.println(granted.toString());
                        if (isAll && permissionDialog.isShowing()) {
                            permissionDialog.dismiss();
                        }
                        if (UpdateUtils.OPEN_TAG==1){
                            checkupdate();
                        }
                    }

                    @Override
                    public void noPermission(List<String> denied, boolean quick) {
                        if (null != permissionDialog && !permissionDialog.isShowing())
                            permissionDialog.show();
                        permissionDialog.setConfirmListener(() -> XXPermissions.gotoPermissionSettings(MainActivity.this));
                    }
                });

    }

    /**
     * 初始化组件
     */
    private void initView() {
        //实例化布局对象
        layoutInflater = LayoutInflater.from(this);
        rgMain = findViewById(R.id.rg_main);

        fragments = new ArrayList<>();
        fragments.add(new HomeFragment());
        fragments.add(new HouseFragment());
        fragments.add(new CustomerFragment());
        if (BuildConfig.bbsActivity==null){
            findViewById(R.id.emptyView).setVisibility(View.GONE);
            findViewById(R.id.rb_message).setVisibility(View.VISIBLE);
            findViewById(R.id.bbsHomeImageView).setVisibility(View.GONE);
            fragments.add(new MessageFragment());
        }else {
            findViewById(R.id.emptyView).setVisibility(View.VISIBLE);
            findViewById(R.id.rb_message).setVisibility(View.GONE);
            findViewById(R.id.bbsHomeImageView).setVisibility(View.VISIBLE);
            findViewById(R.id.bbsHomeImageView).setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    toBBSActivity();
                }
            });
        }
        fragments.add(new PersonalFragment());
        Fragment fragment = getFragment(0);

        switchFragment(tempFragment, fragment);
    }

    private void toBBSActivity(){
        if (BuildConfig.bbsActivity!=null){
            Intent intent = new Intent();
            intent.setClass(MainActivity.this, BuildConfig.bbsActivity);
            startActivity(intent);
        }
    }

    @Subscriber(tag = "TAG_HOME_SEARCH")
    private void change2House(String s) {
        rgMain.check(R.id.rb_house);
        switchFragment(tempFragment,getFragment(1));
    }

    private long firstTime = 0;

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        long secondTime = System.currentTimeMillis();
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            if (secondTime - firstTime < 2000) {
                finish();
            } else {
                Toast.makeText(MainActivity.this, "再按一次退出程序", Toast.LENGTH_SHORT).show();
                firstTime = System.currentTimeMillis();
            }
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (firstTime != 0) {
            System.exit(0);
        }
    }

    public interface HomeFragmentIsShowListener{
        void onHomeFragmentShow();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (getSupportFragmentManager().getFragments().size() > 0) {
            List<Fragment> fragments = getSupportFragmentManager().getFragments();
            for (Fragment mFragment : fragments) {
                mFragment.onActivityResult(requestCode, resultCode, data);
            }
        }

    }
}
